package com.hangzhou.xyj.ui.activity;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;

import com.hangzhou.xyj.R;
import com.hangzhou.xyj.XYJApplication;
import com.hangzhou.xyj.db.UserDao;
import com.hangzhou.xyj.db.preferences.CommonPreferences;
import com.hangzhou.xyj.event.CorrectRespEvent;
import com.hangzhou.xyj.manager.IntentManager;
import com.hangzhou.xyj.model.UserModel;
import com.hangzhou.xyj.model.type.ECorrectType;
import com.hangzhou.xyj.model.type.EIntentTagType;
import com.hangzhou.xyj.net.http.HttpLoader;
import com.hangzhou.xyj.net.okhttp.listener.impl.UIProgressListener;
import com.hangzhou.xyj.net.response.base.BaseResponse;
import com.hangzhou.xyj.ui.activity.base.BaseActivity;
import com.hangzhou.xyj.ui.dialog.TipsDialog;
import com.hangzhou.xyj.ui.widget.CircleImageView;
import com.hangzhou.xyj.ui.widget.ClickItemView;
import com.hangzhou.xyj.ui.widget.multiimageselector.MultiImageSelectorActivity;
import com.hangzhou.xyj.ui.widget.views.MyTextView;
import com.hangzhou.xyj.utils.EventBusUtil;
import com.hangzhou.xyj.utils.PublicUtil;
import com.hangzhou.xyj.utils.constants.API;
import com.hangzhou.xyj.utils.constants.DataKey;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.greenrobot.eventbus.Subscribe;

import java.util.List;
import java.util.Map;

public class MyPersonalInfoActivity extends BaseActivity {
    public static final int REQUEST_CODE_CORRECT_NAME = 1;
    public static final int REQUEST_CODE_CORRECT_SIGN = 2;
    public static final int REQUEST_CODE_CORRECT_GENDER = 3;
    public static final int REQUEST_CODE_IMAGE = 5;
    public static final int REQUEST_CODE_CORRECT_DISTRICT = 6;
    private final String TAG = "MyPersonalInfoActivity";
    ClickItemView mClvName;//名字
    ClickItemView mClvGender;//性别
    ClickItemView mClvHobby;//爱好
    ClickItemView mClvTeacher;//师从
    ClickItemView mClvDistrict;//地区
    ClickItemView mClvSign;//签名
    ClickItemView mClvAuthen;//认证
    CircleImageView mCivHeader;//头像

    private Handler mHanler;

    UserModel userModel;
    private String mFilePath;
    private String mHeadImgUrl;

    private int mCheckFlag;

    @Override
    public void initTop() {
        enableTitle(true, "个人信息");
    }

    @Override
    public void initLayouts() {
        setContentView(R.layout.activity_mine_personal_info);
    }

    @Override
    public void initViews() {
        mClvName = (ClickItemView) findViewById(R.id.civ_my_namea);
        mClvGender = (ClickItemView) findViewById(R.id.civ_my_gender);
        mClvHobby = (ClickItemView) findViewById(R.id.civ_my_hobby);
        mClvTeacher = (ClickItemView) findViewById(R.id.civ_my_teacher);
        mClvDistrict = (ClickItemView) findViewById(R.id.civ_my_district);
        mClvSign = (ClickItemView) findViewById(R.id.civ_my_signature);
        mClvAuthen = (ClickItemView) findViewById(R.id.civ_my_authen);
        mCivHeader = (CircleImageView) findViewById(R.id.civ_header);
    }

    @Override
    public void initDatas() {
        userModel = XYJApplication.getUserInfo();
        setData(userModel);
        mHanler = new Handler(getMainLooper()) {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 1:
                        ImageLoader.getInstance().displayImage("file://" + mFilePath, mCivHeader);
                        //更新应用中的信息
                        XYJApplication.getInstance().getUserInfo().setHeadPic(mHeadImgUrl);
                        //更新本地数据库中的信息
                        UserDao dao = new UserDao(mContext);
                        dao.addUser(XYJApplication.getInstance().getUserInfo());
                        CorrectRespEvent event = new CorrectRespEvent();
                        event.setTag(ECorrectType.HEAD_IMG.getValue());
                        event.setValue(mFilePath);
                        EventBusUtil.postEvent(event);
                        break;
                    default:
                        break;
                }
            }
        };
    }

    @Override
    public void initListeners() {
        EventBusUtil.register(this);//注册EventBus
        mCivHeader.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, MultiImageSelectorActivity.class);
                // 是否显示调用相机拍照
                intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
                // 最大图片选择数量
                intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 9);
                // 设置模式 (支持 单选/MultiImageSelectorActivity.MODE_SINGLE 或者 多选/MultiImageSelectorActivity.MODE_MULTI)
                intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_SINGLE);
                IntentManager.getInstance().goImageSelectorActivity(MyPersonalInfoActivity.this, intent, REQUEST_CODE_IMAGE);
            }
        });
        mClvName.setOnClickListener(
                new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // 获取名字值
                        String name = ((MyTextView) v
                                .findViewById(R.id.tv_item_view_right))
                                .getText().toString().trim();
                        Intent intent = new Intent(MyPersonalInfoActivity.this,
                                MyCorrectNameActivity.class);
                        intent.putExtra("value", name);
                        intent.putExtra("userId", userModel.getUserId());
                        IntentManager.getInstance().goCorrectActivity(
                                MyPersonalInfoActivity.this, intent,
                                REQUEST_CODE_CORRECT_NAME);
                    }
                });
        mClvGender.setOnClickListener(
                new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String value = ((MyTextView) v
                                .findViewById(R.id.tv_item_view_right))
                                .getText().toString().trim();
                        Intent intent = new Intent(MyPersonalInfoActivity.this,
                                MyCorrectGenderActivity.class);
                        intent.putExtra("value", value);
                        IntentManager.getInstance().goCorrectActivity(
                                MyPersonalInfoActivity.this, intent,
                                REQUEST_CODE_CORRECT_GENDER);
                    }
                });
        mClvHobby.setOnClickListener(
                new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(mContext, DramaCategoryListActivity.class);
                        intent.putExtra(DataKey.INTENT_TAG, EIntentTagType.TAG_MINE_PERSONAL_INFO.getValue());
                        intent.putExtra(DataKey.TITLE, "剧种");
                        IntentManager.getInstance().goActivity(mContext, intent);
                    }
                });
        mClvTeacher.setOnClickListener(
                new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // 获取值
                        String value = ((MyTextView) v
                                .findViewById(R.id.tv_item_view_right))
                                .getText().toString().trim();
                        Intent intent = new Intent(MyPersonalInfoActivity.this,
                                MyCorrectTeacherActivity.class);
                        intent.putExtra("value", value);
                        IntentManager.getInstance().goActivity(mContext, intent);
                    }
                });
        mClvDistrict.setOnClickListener(
                new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        IntentManager.getInstance().goSelectCityActivity(MyPersonalInfoActivity.this, new Intent(MyPersonalInfoActivity.this, SelectCityActivity.class), REQUEST_CODE_CORRECT_DISTRICT);
                    }
                });
        mClvSign.setOnClickListener(
                new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String value = ((MyTextView) v
                                .findViewById(R.id.tv_item_view_right))
                                .getText().toString().trim();
                        Intent intent = new Intent(MyPersonalInfoActivity.this,
                                MyCorrectSignActivity.class);
                        intent.putExtra("value", value);
                        IntentManager.getInstance().goActivity(mContext, intent);
                    }
                });
        mClvAuthen.setOnClickListener(
                new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        switch (mCheckFlag) {
                            case 1:
                            case 2:
                            case 3:
                                new TipsDialog(mContext, "恭喜，您完成认证！", "确定").show();
                                break;
                            case 0:
                            case 4:
                                IntentManager.getInstance().goMyAuthenDialogActivity(MyPersonalInfoActivity.this);
                                break;
                            case 5:
                            case 6:
                                new TipsDialog(mContext, "认证已经在审核中", "确定").show();
                                break;

                        }
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode,
                                    Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);

        if (requestCode == REQUEST_CODE_CORRECT_NAME && resultCode == 1) {
            mClvName.setRightText(intent.getStringExtra("value"));
        }

        if (requestCode == REQUEST_CODE_CORRECT_SIGN && resultCode == 1) {
            mClvSign.setRightText(intent.getStringExtra("value"));
        }

        if (requestCode == REQUEST_CODE_CORRECT_GENDER && resultCode == 1) {
            mClvGender.setRightText(intent.getStringExtra("value"));
        }

        if (requestCode == REQUEST_CODE_IMAGE && resultCode == RESULT_OK) {
            // 获取返回的图片列表
            List<String> path = intent.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
            mFilePath = path.get(0);
            HttpLoader.getInstance().uploadHeadImg(mFilePath, CommonPreferences.getUserId(mContext),
                    API.UPDATE_HEAD, PublicUtil.compressImage(BitmapFactory.decodeFile(mFilePath)), new UIProgressListener() {
                        @Override
                        public void onUIStart() {

                        }

                        @Override
                        public void onUIProgress(long currentBytes, long contentLength, boolean done) {

                        }

                        @Override
                        public void onUIFinish(BaseResponse response) {
                            if (response.isSuccess()) {
                                mHanler.sendEmptyMessage(1);
                                Map<String, String> map = (Map<String, String>) response.getData();
                                mHeadImgUrl = map.get("head_pic");
                            }
                        }
                    });
        }
    }

    public void setData(UserModel data) {
        mClvName.setRightText(data.getNickName());//名称
        mClvGender.setRightText(data.getSex());//性别
        mClvHobby.setRightText(data.getHobby());//爱好
        mClvTeacher.setRightText(data.getTeacher());//师从
        mClvDistrict.setRightText(data.getZone());//地区
        mClvSign.setRightText(data.getSignature());//个性签名
        mClvAuthen.setRightIcon(PublicUtil.getAuthenIconStringUri(mContext, data.getUserType()));//设置认证图片
        //设置头像
        mCivHeader.displayImage(data.getHeadPic());
        mCheckFlag = data.getCheckFlag();
    }

    @Subscribe
    public void onEventMainThread(CorrectRespEvent event) {
        switch (ECorrectType.valueOf(event.getTag())) {
            case HOBBY:
                mClvHobby.setRightText(event.getValue());//爱好
                break;
            case TEACHER:
                mClvTeacher.setRightText(event.getValue());//师从
                break;
            case SIGN:
                mClvSign.setRightText(event.getValue());//个性签名
                break;
            case AUTHEN:
                break;
            case ZONE:
                mClvDistrict.setRightText(event.getValue());//地区
        }
    }

}
